package com.iflytek.springboot_medicine.controller;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class DeepSeekClient {
    private static String API_KEY;
    private static String API_URL;

    static {
        Properties properties = new Properties();
        try {
            InputStream inputStream = DeepSeekClient.class.getResourceAsStream("/config.properties");
            properties.load(inputStream);
            API_KEY = properties.getProperty("key");
            API_URL = properties.getProperty("url");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("~~~~我是deepseek，很高兴认识你~~~~~");
        while (true) {
            System.out.println("请说出你的问题");
            String question = scanner.nextLine();
            if ("bye".equals(question)) {
                break;
            }
            ask(question);
            System.out.println();
        }
        System.out.println("拜拜，欢迎下次光临！");
    }

    public static void ask(String question) {
        List<Message> messages = new ArrayList<>();
        messages.add(new Message("user", question));

        ChatRequest requestBody = new ChatRequest(
                "deepseek-chat",
                messages,
                0.7,
                1000
        );
        System.out.println("正在提交问题>>>");
        long startTime = System.currentTimeMillis();

        String response = sendRequest(requestBody);
        long endTime = System.currentTimeMillis();
        System.out.println("思考用时 " + (endTime - startTime) + " ms");
        System.out.println("回答： " + response);
    }

    private static String sendRequest(ChatRequest requestBody) {
        Gson gson = new Gson();
        String requestBodyJson = gson.toJson(requestBody);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(30, TimeUnit.SECONDS)
                .setConnectionRequestTimeout(30, TimeUnit.SECONDS)
                .setResponseTimeout(30, TimeUnit.SECONDS)
                .build();
        try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build()) {
            HttpPost request = new HttpPost(API_URL);
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Authorization", "Bearer " + API_KEY);
            request.setEntity(new StringEntity(requestBodyJson, ContentType.APPLICATION_JSON));

            try (CloseableHttpResponse response = client.execute(request)) {
                if (response.getCode() == 200) {
                    String responseContent = EntityUtils.toString(response.getEntity());
                    System.out.println("Response content: " + responseContent);

                    try {
                        ChatResponse chatResponse = gson.fromJson(responseContent, ChatResponse.class);
                        return chatResponse.getChoices().get(0).getMessage().getContent();
                    } catch (JsonSyntaxException e) {
                        return "响应内容不是有效的JSON格式: " + responseContent;
                    }
                } else {
                    return "请求状态码: " + response.getCode() + ", 响应: " + EntityUtils.toString(response.getEntity());
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "请求异常: " + e.getMessage();
        }
    }

    static class Message {
        private String role;
        private String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }
        public String getContent() {
            return content;
        }
    }

    static class ChatRequest {
        private String model;
        private List<Message> messages;
        private double temperature;
        private int max_tokens;

        public ChatRequest(String model, List<Message> messages, double temperature, int max_tokens) {
            this.model = model;
            this.messages = messages;
            this.temperature = temperature;
            this.max_tokens = max_tokens;
        }
    }

    static class ChatResponse {
        private List<Choice> choices;

        public List<Choice> getChoices() {
            return choices;
        }

        static class Choice {
            private Message message;

            public Message getMessage() {
                return message;
            }
        }
    }
}
